package com.dxy.app.widget.switch_view;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.dxy.app.R;
import com.dxy.app.widget.ThreadManager;

/**
  *Created by duxingyu on 2017/7/24.17:48
  *Email: 
  *Description:开关控件
  **/

public class SwitchView extends View {

  public static final String TAG="TAG_";

  /**
   * 画笔
   * */
  private Paint paint;
  /**
   * 绘制阴影的画笔
   * */
  private Paint shadowPaint;
  /**
   * 阴影半径
   * */
  private int offPixs=3;
  /**
   * 偏移量
   * */
  private int curSwitchOffsetX;
  /**
   * 当前是否绘制完成
   * */
  private boolean inMoving =false;
  /**
   * 状态
   * */
  private boolean isOpenState =true;
  /**
   * 一些变量
   * */
  private int cornerRadius,//圆角半径
      width,//控件宽度
      height;//控件高度
  /**
   * 所需的颜色资源
   * */
  private int openColorBg,//处于打开状态下的背景颜色
      closeColorBg,//关闭状态下的背景颜色
      colorSwitch;//开关的颜色
  /**
   * 左边的半圆形区域，右边的半圆形区域
   * */
  private RectF leftCircle,rightCircle;

  public SwitchView(Context context) {
    super(context);
    init(null);
  }

  public SwitchView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray array =context.obtainStyledAttributes(attrs, R.styleable.SwitchView);
    init(array);
  }

  public SwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray array =context.obtainStyledAttributes(attrs, R.styleable.SwitchView);
    init(array);
  }

  private void init(TypedArray array){
    if(array!=null){
      openColorBg =array.getColor(R.styleable.SwitchView_switch_back_ground, Color.GREEN);
      colorSwitch =array.getColor(R.styleable.SwitchView_switch_color, Color.WHITE);
      width =array.getDimensionPixelSize(R.styleable.SwitchView_switch_width,50);
      height =array.getDimensionPixelSize(R.styleable.SwitchView_switch_corner,25);
      array.recycle();
    }else{
      float disteny = Resources.getSystem().getDisplayMetrics().density;
      openColorBg = Color.GREEN;
      colorSwitch = Color.WHITE;
      width = (int) (50*disteny);
      height = (int) (25*disteny);
    }
    closeColorBg = Color.parseColor("#cccccc");
    cornerRadius =height/2;
    curSwitchOffsetX =width-cornerRadius;
    paint =new Paint();
    paint.setAntiAlias(true);


    shadowPaint =new Paint();
    shadowPaint.setAntiAlias(true);
    shadowPaint.setShadowLayer(2,-2,2, Color.parseColor("#888888"));
    shadowPaint.setColor(colorSwitch);

    setLayerType(LAYER_TYPE_SOFTWARE,shadowPaint);//设置阴影效果

    leftCircle =new RectF(0,0,height,height);
    rightCircle =new RectF(width-height,0,width,height);
  }


  @Override protected void onDraw(Canvas canvas) {
    if(isOpenState){
      paint.setColor(openColorBg);
    }else{
      paint.setColor(closeColorBg);
    }
    canvas.drawArc(leftCircle,90,180,true,paint);
    canvas.drawRect(cornerRadius,0,width-cornerRadius,height,paint);
    canvas.drawArc(rightCircle,270,180,true,paint);

    canvas.drawCircle(curSwitchOffsetX,cornerRadius,cornerRadius-offPixs,shadowPaint);
  }

  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(width,height);
  }

  @Override public boolean onTouchEvent(MotionEvent event) {
    if(inMoving){
      return false;
    }
    inMoving =true;
    startTask();
    return true;
  }
  public void setState(boolean isOpen){
    isOpenState =isOpen;
    if(isOpen){
      curSwitchOffsetX =width-cornerRadius;
    }else{
      curSwitchOffsetX =cornerRadius;
    }
    invalidate();
  }

  private Handler handler =new Handler(){
    @Override public void handleMessage(Message msg) {
      if(isOpenState&&inMoving){
        curSwitchOffsetX-=5;
        if(curSwitchOffsetX<cornerRadius){
          curSwitchOffsetX =cornerRadius;
          inMoving =false;
          isOpenState =false;
          if(callBack!=null){
            callBack.curState(false);
          }
        }
      }else{
        if(!inMoving){
          return;
        }
        curSwitchOffsetX+=5;
        if(curSwitchOffsetX>width-cornerRadius){
          curSwitchOffsetX =width -cornerRadius;
          inMoving =false;
          isOpenState =true;
          if(callBack!=null){
            callBack.curState(true);
          }
        }
      }
      invalidate();
    }
  };
  private void startTask(){
    ThreadManager.getShortPool().execute(()->{
      while(inMoving){
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        handler.sendEmptyMessage(0);
      }
    });
  }
  private StateCallBack callBack;
  public void setCallBack(StateCallBack callBack){
    this.callBack =callBack;
  }
}

